<?php

if (!defined('TOBBIVM'))
	header('location:/template/notrepassing.php');
/**
 * This file is part of TobbiVMShop.
 *
 * TobbiVMShop is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TobbiVMShop is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TobbiVMShop.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Authenticate data from Login
 *
 * @version    $Id$
 * @package    TobbiVM-Shop
 * @copyright  Copyright (C) 2012
 * @author     Norbert Gebert
 * @license    GPL3
 *
 *
 */

/**
 * Verify User-Input from Login-Form
 *
 * @param  string $user     Username
 * @param  string $password Userpassword
 * @return mixed  returns true if Login ok
 */
function loginUser($user, $password)
{
	db::getInstance()->where("user_name", $user);
	db::getInstance()->where("user_active", 1);
	$result = db::getInstance()->getOne("user");

	if ($result !== NULL)
	{
		// If a record is found, the username exists,
		// so we check if the credentials are correct
		// Login password to prepare
		$secureid = $result['user_secureid'];
		$userpw = md5($password . $secureid);

		$cols = Array('user_id', 'user_errors', 'user_text');
		db::getInstance()->where("user_name", $user);
		db::getInstance()->where("user_password", $userpw);
		db::getInstance()->where("user_active", 1);
		$result = db::getInstance()->get("user", null, $cols);

		if (db::getInstance()->count >= 1)
		{ // Checking if a record was found. In the case of voting credentials
			// Reset counter, update Logdata
			$logRows = explode("<br>", $result[0]['user_text']);
			$logEntrys = count($logRows);
			
			if ($logEntrys >= 100)
			{
				//for ($a = 0; $a = ($logEntrys - 99); $a++) 
				//{echo '3-'.$a.'<br>';
					unset($logRows[0]);
				//}
				//$array = array_values($array);

				$logText = date("Y-m-d H:i:s") . ';' . $_SERVER['HTTP_USER_AGENT'] . ';' .
					$_SERVER['REMOTE_ADDR'] . "<br>";

				foreach ($logRows as $row)
				{
					$logText .= $row . "\n";
				}
			}
			else
			{
				$logText = date("Y-m-d H:i:s") . ';' . $_SERVER['HTTP_USER_AGENT'] . ';' .
					$_SERVER['REMOTE_ADDR'] . "<br>" . $result[0]['user_text'];
			}
			//var_dump($result);echo $result[0]['user_text'];exit;
			$data = Array('user_errors' => 0,
			 'user_text' => $logText);
			db::getInstance()->where('user_name', $user);
			db::getInstance()->update('user', $data);
			return TRUE;
		}
		else
		{
			// The given password was incorrect, so we go from a trial
			// error and increase the counter of failed logon attempts
			db::getInstance()->where("user_name", $user);
			db::getInstance()->where("user_active", 1);
			$result = db::getInstance()->getOne("user");
			$errors = $result['user_errors'];

			// Update the database
			$data = Array('user_errors' => ($errors + 1));
			db::getInstance()->where('user_name', $user);
			db::getInstance()->where("user_active", 1);
			db::getInstance()->update('user', $data);

			// if the limit has been reached of 10 failed attempts, in this case ...
			// ...deactivate the user
			if (($errors + 1) > 9)
			{
				$data = Array('user_active' => 0,
				 'user_errors' => 0);
				db::getInstance()->where('user_name', $user);
				db::getInstance()->update('user', $data);
			}
			return FALSE;
		}
	}
	return FALSE;
}

/**
 * Update Userdata
 *
 * @param  string $user     Username
 * @return mixed  returns true if the update ok
 */
function updateUser($user)
{
	$data = Array('user_ip' => $_SERVER['REMOTE_ADDR'],
	 'user_info' => $_SERVER['HTTP_USER_AGENT'],
	 'user_login' => md5($_SERVER['REQUEST_TIME']),
	 'user_lastonline' => date("Y-m-d H:i:s"));
	db::getInstance()->where('user_name', $user);

	if (db::getInstance()->update('user', $data))
	{
		// Set Session variable
		$_SESSION['active'] = true;
		$_SESSION['username'] = $user;
		$_SESSION['login'] = md5($_SERVER['REQUEST_TIME']);
		return true;
	}
	else
	{
		return false;
	}
}

/**
 * Check user and regenerate Session
 *
 * @return mixed  returns true if the update ok
 */
function checkUser()
{ // Clear old Session and transfer Sessiondata in new Session
	session_regenerate_id(true);
	if (isset($_SESSION['active']) and $_SESSION['active'] !== true)
		return false;
	// Read Userdata from DB
	db::getInstance()->where("user_name", $_SESSION['username']);
	db::getInstance()->where("user_active", 1);
	$result = db::getInstance()->getOne("user");

	if (db::getInstance()->count >= 1)
	{ // Check Data from DB and compare with the user data
		if ($result['user_ip'] != $_SERVER['REMOTE_ADDR'] or
			$result['user_info'] != $_SERVER['HTTP_USER_AGENT'] or
			$result['user_login'] != $_SESSION['login'] or
			(strtotime($result['user_lastonline']) + TIMEOUT) <= time())
			resetUser();
	}
	else
	{
		resetUser();
	}

	// If Userdata ok update last activity
	$data = Array('user_lastonline' => date("Y-m-d H:i:s"));
	db::getInstance()->where('user_name', $_SESSION['username']);

	if (db::getInstance()->update('user', $data))
		return TRUE;
	return False;
}

/**
 * Destroy session for Logout
 *
 * @param  none
 * @return none
 */
function resetUser()
{
	/* session_destroy();
	  $_SESSION['active'] = false;
	  $_SESSION['username'] = ''; */
	// Clear session
	session_unset();
	// Definitely go all the contents of the session are deleted
	$_SESSION = array();
	// delete session
	session_destroy();
	// Start new session
	session_start();
	// New server-generated session ID
	session_regenerate_id();
	// hold status
	$_SESSION['server_SID'] = true;
	header('location: index.php');
	exit;
}

?>